// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class Heibaipei extends cc.Component {


    @property(cc.Prefab)
    fruit: cc.Prefab = null;

    timer: number = 0;
    sudu: number = 3;

    static score: number = 0;
    static running: boolean = false;
    @property(cc.Label)
    scoreLabel: cc.Label = null;

    @property(cc.Node)
    basket: cc.Node[] = [];
    @property(cc.Node)
    resetLabel: cc.Node = null;

    start() {
        cc.director.getCollisionManager().enabled = true; // 开启碰撞检测 全局的，在程序运行时任何一个地方开启即可
        this.reset();
    }

    reset(){
        Heibaipei.score = 0;
        Heibaipei.running = true;
        this.resetLabel.active = false;
        for (let i = 0, j = this.basket.length; i < j; i++) {
            let nub = Math.random();
            this.basket[i].group = nub > 0.5 ? "whiteBasket" : "blackBasket";
            this.basket[i].color = nub > 0.5 ? cc.color(255, 255, 255) : cc.color(0, 0, 0);
        }
    }

    update(dt) {
        this.timer += dt;
        if (Heibaipei.running && (this.timer - this.sudu) > 0) {
            this.timer = 0;
            let loadobj = cc.instantiate(this.fruit);//将预制体克隆到场景
            this.node.addChild(loadobj);//将克隆出的物体作为子物体
            loadobj.setPosition(new cc.Vec2(1000,90000));
            loadobj.width = 75;
            let nub = Math.random();
            loadobj.group = nub > 0.5 ? "white" : "black";
            loadobj.color = nub > 0.5 ? cc.color(255, 255, 255) : cc.color(0, 0, 0);
        }
        this.scoreLabel.string = Heibaipei.score.toString();
        if(!Heibaipei.running){
            this.resetLabel.active = true;
        }
    }

    static addScore() {
        Heibaipei.score++;
    }

    static over() {
        Heibaipei.running = false;

    }

    // 更换篮子的分组和颜色
    trade(){
        for (let i = 0, j = this.basket.length; i < j; i++) {
            if(this.basket[i].group == "whiteBasket"){
                this.basket[i].group = "blackBasket";
                this.basket[i].color =  cc.color(0, 0, 0);
            }else{
                this.basket[i].group = "whiteBasket";
                this.basket[i].color =  cc.color(255, 255, 255);
            }
        }
    }
}
